package Utils;

import annotation.Bean;
import component.Ioc;

import java.io.File;

public class LoadClassBean {
    protected static void dealDir(String filepath) throws ReflectiveOperationException {
        File file = new File(LoadClassBean.class.getResource(filepath).getPath());
        String[] names = file.list();
        for(String str : names){
            str = filepath+str;
            file = new File(LoadClassBean.class.getResource(str).getPath());
            if(file.isDirectory()){
                dealDir(str+"/");
            }else{
                if(str.endsWith(".class")){
                    str = str.substring(1,str.length()-6).replaceAll("/",".");
                    dealClass(str);
                }
            }
        }
    }
    protected static void dealClass(String filepath) throws ReflectiveOperationException {
        Class<?> klass = Class.forName(filepath);
        if(klass.getAnnotation(Bean.class) != null){
            Ioc ioc = Ioc.getIoc();
            String alise = klass.getDeclaredAnnotation(Bean.class).Alise();
            boolean Sington = klass.getAnnotation(Bean.class).SingleTon();
            Object object = klass.getDeclaredConstructor().newInstance();
            if (alise == null || alise == "" || alise.isEmpty()){
                String[] names = filepath.split("\\.");
                alise = names[names.length-1];
            }
            if(Sington == false){ //多例模式，保存全类名，方便反射生成
                ioc.insertFactoryBean(alise,filepath);
                return;
            }
            ioc.insertFactoryBean(alise,object);
        }
    }

    /**
     * 启动注入，将Bean注解及Controller注解类，注入
     */
    public static void run(){
        try {
            dealDir("/");
            LoadClassController.dealDir("/");
            //System.out.println("run");
        } catch (ReflectiveOperationException e) {
            e.printStackTrace();
        }
    }
}
